package org.zheng.shop.service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zheng.shop.dto.ConsultationMessageDTO;
import org.zheng.shop.dto.ConsultationSessionDTO;
import org.zheng.shop.entity.ConsultationMessage;
import org.zheng.shop.entity.ConsultationSession;
import org.zheng.shop.entity.User;
import org.zheng.shop.repository.ConsultationMessageRepository;
import org.zheng.shop.repository.ConsultationSessionRepository;
import org.zheng.shop.repository.UserRepository;

/**
 * 咨询服务 - 基于轮询的简单实现
 */
@Service
@Transactional
public class ConsultationService {

    @Autowired
    private ConsultationSessionRepository sessionRepository;

    @Autowired
    private ConsultationMessageRepository messageRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 创建或获取用户的活跃咨询会话
     */
    public ConsultationSessionDTO createOrGetActiveSession(Integer userId, String title) {
        // 查找用户的所有会话，然后筛选活跃的
        List<ConsultationSession> allUserSessions = sessionRepository
            .findByUserIdOrderByUpdatedAtDesc(userId);

        // 筛选出活跃的会话
        List<ConsultationSession> activeSessions = allUserSessions.stream()
            .filter(session -> session.getStatus() == ConsultationSession.SessionStatus.WAITING ||
                             session.getStatus() == ConsultationSession.SessionStatus.ACTIVE)
            .collect(Collectors.toList());

        if (!activeSessions.isEmpty()) {
            // 如果有多个活跃会话，返回最新的一个，并关闭其他的
            ConsultationSession latestSession = activeSessions.get(0);

            // 关闭其他重复的会话
            for (int i = 1; i < activeSessions.size(); i++) {
                ConsultationSession duplicateSession = activeSessions.get(i);
                duplicateSession.setStatus(ConsultationSession.SessionStatus.CLOSED);
                sessionRepository.save(duplicateSession);
                System.out.println("关闭重复会话: " + duplicateSession.getId());
            }

            return new ConsultationSessionDTO(latestSession);
        }

        // 创建新会话
        Optional<User> user = userRepository.findById(userId);
        if (user.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }

        ConsultationSession session = new ConsultationSession();
        session.setUserId(userId);
        session.setUserName(user.get().getUsername());
        session.setTitle(title != null ? title : "在线咨询");
        session.setStatus(ConsultationSession.SessionStatus.WAITING);
        session.setCreatedAt(LocalDateTime.now());
        session.setUpdatedAt(LocalDateTime.now());

        session = sessionRepository.save(session);

        // 发送欢迎消息
        sendSystemMessage(session.getId(), "欢迎使用在线咨询服务，客服将尽快为您服务！");

        return new ConsultationSessionDTO(session);
    }

    /**
     * 检查用户是否可以访问会话
     */
    public boolean canAccessSession(Long sessionId, Integer userId) {
        Optional<ConsultationSession> session = sessionRepository.findById(sessionId);
        if (session.isEmpty()) {
            return false;
        }

        // 用户可以访问自己的会话，管理员可以访问所有会话
        return session.get().getUserId().equals(userId) || isAdmin(userId);
    }

    /**
     * 获取指定时间戳之后的消息
     */
    public List<ConsultationMessageDTO> getMessagesSince(Long sessionId, Long since) {
        LocalDateTime sinceTime;
        if (since != null) {
            // 将毫秒时间戳转换为LocalDateTime
            sinceTime = LocalDateTime.ofInstant(
                java.time.Instant.ofEpochMilli(since),
                java.time.ZoneId.systemDefault()
            );
        } else {
            // 默认获取24小时内的消息
            sinceTime = LocalDateTime.now().minusHours(24);
        }

        List<ConsultationMessage> messages = messageRepository
            .findBySessionIdAndSentAtAfterOrderBySentAtAsc(sessionId, sinceTime);

        return messages.stream()
            .map(ConsultationMessageDTO::new)
            .collect(Collectors.toList());
    }

    /**
     * 发送消息
     */
    public ConsultationMessageDTO sendMessage(Long sessionId, Integer senderId, String content, boolean isAdmin) {
        // 验证会话存在
        Optional<ConsultationSession> sessionOpt = sessionRepository.findById(sessionId);
        if (sessionOpt.isEmpty()) {
            throw new RuntimeException("会话不存在");
        }

        ConsultationSession session = sessionOpt.get();

        // 获取发送者信息
        Optional<User> sender = userRepository.findById(senderId);
        if (sender.isEmpty()) {
            throw new RuntimeException("发送者不存在");
        }

        // 创建消息
        ConsultationMessage message = new ConsultationMessage();
        message.setSessionId(sessionId);
        message.setSenderId(senderId);
        message.setSenderName(sender.get().getUsername());
        message.setContent(content);
        message.setSenderType(isAdmin ? 
            ConsultationMessage.SenderType.ADMIN : 
            ConsultationMessage.SenderType.USER);
        message.setSentAt(LocalDateTime.now());

        message = messageRepository.save(message);

        // 更新会话信息
        session.setLastMessageAt(LocalDateTime.now());
        session.setUpdatedAt(LocalDateTime.now());
        if (!isAdmin) {
            // 用户发送消息时，如果会话是等待状态，保持等待；如果是活跃状态，保持活跃
            // 管理员发送消息时，将会话设为活跃
        } else {
            session.setStatus(ConsultationSession.SessionStatus.ACTIVE);
            session.setAdminId(senderId);
        }
        sessionRepository.save(session);

        return new ConsultationMessageDTO(message);
    }

    /**
     * 发送系统消息
     */
    private void sendSystemMessage(Long sessionId, String content) {
        ConsultationMessage message = new ConsultationMessage();
        message.setSessionId(sessionId);
        message.setSenderId(0); // 系统消息使用ID 0
        message.setSenderName("系统");
        message.setContent(content);
        message.setSenderType(ConsultationMessage.SenderType.SYSTEM);
        message.setSentAt(LocalDateTime.now());

        messageRepository.save(message);
    }

    /**
     * 获取用户的会话列表
     */
    public List<ConsultationSessionDTO> getUserSessions(Integer userId) {
        List<ConsultationSession> sessions = sessionRepository
            .findByUserIdOrderByUpdatedAtDesc(userId);
        
        return sessions.stream()
            .map(ConsultationSessionDTO::new)
            .collect(Collectors.toList());
    }

    /**
     * 获取所有会话列表（管理员）
     */
    public List<ConsultationSessionDTO> getAllSessions() {
        List<ConsultationSession> sessions = sessionRepository
            .findAllByOrderByUpdatedAtDesc();
        
        return sessions.stream()
            .map(ConsultationSessionDTO::new)
            .collect(Collectors.toList());
    }

    /**
     * 管理员接管会话
     */
    public void takeOverSession(Long sessionId, Integer adminId) {
        Optional<ConsultationSession> sessionOpt = sessionRepository.findById(sessionId);
        if (sessionOpt.isEmpty()) {
            throw new RuntimeException("会话不存在");
        }

        ConsultationSession session = sessionOpt.get();
        session.setStatus(ConsultationSession.SessionStatus.ACTIVE);
        session.setAdminId(adminId);
        session.setUpdatedAt(LocalDateTime.now());
        
        sessionRepository.save(session);

        // 发送系统消息
        sendSystemMessage(sessionId, "客服已接入，为您服务");
    }

    /**
     * 检查用户是否是管理员
     */
    private boolean isAdmin(Integer userId) {
        Optional<User> user = userRepository.findById(userId);
        return user.isPresent() && user.get().getIsAdmin();
    }

    /**
     * 清理重复的活跃会话
     */
    public int cleanupDuplicateSessions() {
        int cleanedCount = 0;

        // 获取所有用户
        List<User> allUsers = userRepository.findAll();

        for (User user : allUsers) {
            List<ConsultationSession> allUserSessions = sessionRepository
                .findByUserIdOrderByUpdatedAtDesc(user.getId());

            // 筛选出活跃的会话
            List<ConsultationSession> activeSessions = allUserSessions.stream()
                .filter(session -> session.getStatus() == ConsultationSession.SessionStatus.WAITING ||
                                 session.getStatus() == ConsultationSession.SessionStatus.ACTIVE)
                .collect(Collectors.toList());

            // 如果有多个活跃会话，关闭除了最新的以外的所有会话
            if (activeSessions.size() > 1) {
                for (int i = 1; i < activeSessions.size(); i++) {
                    ConsultationSession duplicateSession = activeSessions.get(i);
                    duplicateSession.setStatus(ConsultationSession.SessionStatus.CLOSED);
                    sessionRepository.save(duplicateSession);
                    cleanedCount++;
                    System.out.println("清理重复会话: 用户" + user.getId() + "的会话" + duplicateSession.getId());
                }
            }
        }

        System.out.println("清理完成，共清理了 " + cleanedCount + " 个重复会话");
        return cleanedCount;
    }

    /**
     * 关闭会话
     */
    public void closeSession(Long sessionId, Integer adminId) {
        Optional<ConsultationSession> sessionOpt = sessionRepository.findById(sessionId);
        if (sessionOpt.isEmpty()) {
            throw new RuntimeException("会话不存在");
        }

        ConsultationSession session = sessionOpt.get();
        session.setStatus(ConsultationSession.SessionStatus.CLOSED);
        session.setUpdatedAt(LocalDateTime.now());

        sessionRepository.save(session);

        // 发送系统消息
        sendSystemMessage(sessionId, "会话已关闭");

        System.out.println("管理员 " + adminId + " 关闭了会话 " + sessionId);
    }

    /**
     * 删除已关闭的会话
     */
    public void deleteClosedSession(Long sessionId) {
        Optional<ConsultationSession> sessionOpt = sessionRepository.findById(sessionId);
        if (sessionOpt.isEmpty()) {
            throw new RuntimeException("会话不存在");
        }

        ConsultationSession session = sessionOpt.get();
        if (session.getStatus() != ConsultationSession.SessionStatus.CLOSED) {
            throw new RuntimeException("只能删除已关闭的会话");
        }

        // 先删除相关的消息
        messageRepository.deleteBySessionId(sessionId);

        // 再删除会话
        sessionRepository.delete(session);

        System.out.println("删除了已关闭的会话 " + sessionId);
    }

    /**
     * 批量删除所有已关闭的会话
     */
    public int deleteAllClosedSessions() {
        List<ConsultationSession> closedSessions = sessionRepository
            .findByStatus(ConsultationSession.SessionStatus.CLOSED);

        int deletedCount = 0;
        for (ConsultationSession session : closedSessions) {
            try {
                // 删除相关的消息
                messageRepository.deleteBySessionId(session.getId());

                // 删除会话
                sessionRepository.delete(session);
                deletedCount++;

                System.out.println("删除了已关闭的会话 " + session.getId());
            } catch (Exception e) {
                System.err.println("删除会话 " + session.getId() + " 失败: " + e.getMessage());
            }
        }

        System.out.println("批量删除完成，共删除了 " + deletedCount + " 个已关闭的会话");
        return deletedCount;
    }
}
